﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
namespace DotNetStar.TheKing.Web.Controllers
{
    using Domain;
    using DotNetStar.TheKing.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Models;
    using Services;
    using System.IO;

    [Route("[controller]")]
    public class CommonController : Controller
    {
        private CommonService _systemService;
        private UserService _userService;
        private ContentService _contentService;
        private IHostingEnvironment _hostingEnvironment;
        private ILogger<CommonController> _logger;
        public CommonController(CommonService systemService,
            UserService userService,
            ContentService contentService,
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory loggerFactory
            )
        {
            _systemService = systemService;
            _userService = userService;
            _contentService = contentService;
            _hostingEnvironment = hostingEnvironment;
            _logger = loggerFactory.CreateLogger<CommonController>();
        }

        [HttpGet("/api/common/pointMessage")]
        public IActionResult GetPointMessageAsyncForAjax()
        {
            return ViewComponent("PointMessage");
        }

        [HttpPost("/api/[controller]/upload/{path}")]
        public async Task<IActionResult> UploadAsync([FromForm]IFormFile file,string path)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName).ToLower();
            var tempPath = $"{_hostingEnvironment.WebRootPath}/upload/temp/";//临时目录

            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            string[] allowExtension = new[] { ".jpg", ".png", ".gif", ".jpeg" };
            long allowSize = 1024 * 1024 * 2;//2MB

            if (file.Length <= 0)
            {
                return BadRequest("附件内容不能是空");
            }

            if (file.Length > allowSize)
            {
                return BadRequest($"附件不能超过{allowSize}MB");
            }

            if (!allowExtension.Contains(extension))
            {
                return BadRequest($"附件仅允许的扩展名为：{allowExtension.Join(";")}");
            }
            var savedTempPath = $"{tempPath}{fileName}";//临时路径
            using (var stream = new FileStream(savedTempPath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            //从临时目录中重命名文件

            var realFilePath = $"{_hostingEnvironment.WebRootPath}/upload/{path}/{DateTime.Now.Year}/{DateTime.Now.Month}";
            var realFileName = $"{realFilePath}/{Guid.NewGuid()}{extension}";
            using (var stream = new FileStream(savedTempPath, FileMode.Open, FileAccess.Read))
            {
                if (!Directory.Exists(realFilePath))
                {
                    Directory.CreateDirectory(realFilePath);
                }

                using (var realStream = new FileStream(realFileName, FileMode.Create))
                {
                    stream.CopyTo(realStream);
                }
            }
            try
            {
                Directory.Delete(tempPath,true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }

            var webFileName = realFileName.Replace(_hostingEnvironment.WebRootPath, string.Empty);
            return Json(new { fileName, webFileName });
        }

    }
}
